package cn.breeze.org.service.impl;

import cn.breeze.basic.constant.BaseConstants;
import cn.breeze.basic.exception.BusinessException;
import cn.breeze.basic.service.impl.BaseServiceImpl;
import cn.breeze.basic.utils.BaiduAuditUtils;
import cn.breeze.basic.utils.SendComplexEmails;
import cn.breeze.org.domain.Employee;
import cn.breeze.org.domain.Shop;
import cn.breeze.org.domain.ShopAuditLog;
import cn.breeze.org.mapper.EmployeeMapper;
import cn.breeze.org.mapper.ShopAuditLogMapper;
import cn.breeze.org.mapper.ShopMapper;
import cn.breeze.org.query.ReportShopQuery;
import cn.breeze.org.service.IEmployeeService;
import cn.breeze.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author breeze
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IEmployeeService iEmployeeService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
    * @Title: settlement
    * @Description: 店铺入驻
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/1 17:38
    * @Parameters: [shop]
    * @Return void
    */
    @Override
    public void settlement(Shop shop) {
        // 手机验证码
        String phoneCodeValue = shop.getPhoneCodeValue();
        // 邮箱验证码
        String emailCodeValue = shop.getEmailCodeValue();
        // 判断手机验证码是否为空
        if (phoneCodeValue == null){
            throw new BusinessException("手机验证码不能为空！");
        }
        // 判断邮箱验证码是否为空
        if (emailCodeValue == null){
            throw new BusinessException("邮箱验证码不能为空！");
        }
        // 获取shop中的员工信息
        Employee admin = shop.getAdmin();
        // 判断店铺名是否为空
        if (StringUtils.isEmpty(shop.getName())){
            throw new BusinessException("店铺名不能为空,请重新输入！");
        }
        // 百度AI判断店铺名是否合规
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BusinessException("店铺名不合规,请重新输入！");
        }
        // 判断管理员账号是否为空
        if (StringUtils.isEmpty(shop.getName())){
            throw new BusinessException("管理员账号不能为空,请重新输入！");
        }
        // 百度AI判断管理员账号名是否合规
        if (!BaiduAuditUtils.TextCensor(admin.getUsername())){
            throw new BusinessException("管理员账号名不合规,请重新输入！");
        }
        // 判断管理员密码是否为空
        if (StringUtils.isEmpty(admin.getPassword())){
            throw new BusinessException("管理员账号密码不能为空,请重新输入！");
        }
        // 判断用户两次输入的密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次输入的密码不一致,请重新输入！");
        }
        // 判断手机验证码是否正确
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + admin.getPhone();
        Object phoneCodeValueTmp = redisTemplate.opsForValue().get(phoneCodeKey);
        if (phoneCodeValueTmp == null){
            throw new BusinessException("手机验证码已过期，请重新获取");
        }
        if (!phoneCodeValue.equalsIgnoreCase(phoneCodeValueTmp.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 判断邮箱验证码是否正确
        Object emailCodeValueTmp = redisTemplate.opsForValue().get(BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + admin.getEmail());
        if (emailCodeValueTmp == null){
            throw new BusinessException("邮箱验证码已过期，请重新获取");
        }
        if (!emailCodeValue.equalsIgnoreCase(emailCodeValueTmp.toString().split(":")[0])){
            throw new BusinessException("邮箱验证码错误，请重新输入！");
        }
        // 百度AI判断店铺logo是否合规
        if (!BaiduAuditUtils.ImgCensorURL(shop.getLogo())){
            throw new BusinessException("店铺logo不合规,请重新上传！");
        }
        if (shop.getId() == null){
            // 判断店铺是否存在
            Shop shopName = shopMapper.loadByName(shop.getName());
            if (shopName != null){
                throw new BusinessException("店铺已存在,请重新输入！");
            }
            // 根据username查询用户是否存在
            Employee employee = employeeMapper.loadByUsername(admin.getUsername());
            // 判断员工是否存在，且该员工是否是店铺管理员
            if (employee != null){
                Shop shop1 = shopMapper.loadByShopId(employee.getId());
                if (shop1 != null){
                    throw new BusinessException("该账户已经存在，且已管理店铺，请重新输入！");
                }
                admin = employee;
            } else {
                // 存入管理员信息
                iEmployeeService.save(admin);
            }

            // 设置店铺的管理员主键id
            shop.setAdminId(admin.getId());
            // 存入店铺信息
            shopMapper.save(shop);
            // 设置店铺管理员的shopId
            admin.setShopId(shop.getId());
            iEmployeeService.update(admin);
        } else {
            /*// 判断员工是否存在，且该员工是否是店铺管理员
            if (employee.getId() != admin.getId()){
                throw new BusinessException("该账户已经存在，请重新输入！");
            }*/
            shopMapper.update(shop);
            iEmployeeService.update(shop.getAdmin());
        }
    }

    /**
    * @Title: auditPass
    * @Description: 审核通过
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/2 17:19
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void auditPass(ShopAuditLog shopAuditLog) {
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.save(shopAuditLog);
        String text = "<h1>店铺审核通知</h1>"+
                "<div>亲，您的店铺审核已通过，请点击下面链接激活！</div>"
                +"激活：<a href='http://localhost:8080/shop/use/activation/"+ shopAuditLog.getShopId() +"'>点击链接立即激活</a>";
        SendComplexEmails.sendEmail(text,"857127444@qq.com");
    }

    /**
    * @Title: auditReject
    * @Description: 审核驳回
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/2 17:19
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.save(shopAuditLog);
        String text = "<h1>店铺审核通知</h1>"+
                "<div>亲，您的店铺审核未通过，请点击下面链接修改店铺信息！</div>"
                +"链接：<a href='http://localhost:8081/#/shopRegister?id="+ shopAuditLog.getShopId() +"'>点击链接修改店铺信息</a>";
        SendComplexEmails.sendEmail(text,"857127444@qq.com");
    }

    /**
    * @Title: auditFail
    * @Description: 审核失败
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/2 17:19
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void auditFail(ShopAuditLog shopAuditLog) {
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.save(shopAuditLog);
        String text = "<h1>店铺审核通知</h1>"+
                "<div>亲，您的店铺审核被拒绝，您可以选择申诉，但我们公司并不受理！</div>";
        SendComplexEmails.sendEmail(text,"857127444@qq.com");
    }

    /**
    * @Title: useActivation
    * @Description: 用户激活
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/3 1:20
    * @Parameters: [id]
    * @Return void
    */
    @Override
    public void useActivation(Long id) {
        shopMapper.updateState(id);
    }

    /**
    * @Title: patchAdd
    * @Description: excel导入
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/3 12:51
    * @Parameters: [shops]
    * @Return void
    */
    @Override
    public void patchAdd(List<Shop> shops) {
        shopMapper.patchAdd(shops);
    }

    /**
    * @Title: reportShop
    * @Description: 店铺报表
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/3 14:31
    * @Parameters: []
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> reportShop() {
        List<ReportShopQuery> reportShopQuery = shopMapper.reportShop();
        List<String> states = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (ReportShopQuery shopQuery : reportShopQuery) {
            counts.add(shopQuery.getCount());
            switch(shopQuery.getState()){
                case 0 :
                    states.add("待审核");
                    break;
                case 1 :
                    states.add("已审核");
                    break;
                case -1 :
                    states.add("驳回");
                    break;
                case 2 :
                    states.add("待激活");
                    break;
                default :
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("x", states);
        map.put("y", counts);
        return map;
    }
}
